﻿using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace modifyTkInfos
{
    public partial class ModifyTkInfoForm : Form
    {
        public ModifyTkInfoForm()
        {
            InitializeComponent();
        }

        private List<string> dwgFiles = new List<string>();

        /// <summary>
        /// 获取选定文件路径下所有dwg文件的名称存储在 dwgFiles中
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            System.Windows.Forms.FolderBrowserDialog folderBrowserDialog = new System.Windows.Forms.FolderBrowserDialog();

            System.Windows.Forms.DialogResult dialogResult = folderBrowserDialog.ShowDialog();

            if (dialogResult != System.Windows.Forms.DialogResult.OK)
            {
                return;
            }

            textBox1.Text = folderBrowserDialog.SelectedPath;

            listBox1.Items.Clear();

            SearchOption searchOption = SearchOption.AllDirectories;

            if (checkBox8.Checked == false)
            {
                searchOption = SearchOption.TopDirectoryOnly;
            }

            dwgFiles.Clear();

            foreach (var item in Directory.GetFiles(textBox1.Text, "*.dwg", searchOption))
            {
                listBox1.Items.Add(item);
                dwgFiles.Add(item);
            }

            if (dwgFiles.Count == 0)
            {
                textBox1.Text = "所选定的文件夹内不含dwg文件，请重新选择文件夹";

                return;
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.Hide();

            if (dwgFiles.Count==0)
            {
                return;
            }

            Dictionary<string, List<string>> fileNameAndTkNamesIn = new Dictionary<string, List<string>>();

            Dictionary<string, List<TkInfo>> fileNameAndTkInfosIn = new Dictionary<string, List<TkInfo>>();

            List<string> finish_files = new List<string>();

            List<string> nms = new List<string>();

            Document doc = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            //逐个处理文件夹中的文件,dwgFiles 为已经赋值的list<string>
            foreach (string drawingFilePath in dwgFiles)
            {
                //逐个文件处理，当发生错误时跳过当前文件。
                try
                {
                    //tkNames_In_File 每个dwg图形中的 图块名称集合
                    //List<string> tkNames_In_File = new List<string>();

                    //tkInfos_In_File 每个dwg图形中的图签信息集合
                    List<TkInfo> tkInfos_In_File = new List<TkInfo>();

                    using (Database database = new Database(false, true))
                    {
                        //读取dwg图形

                        database.ReadDwgFile(drawingFilePath, FileOpenMode.OpenForReadAndWriteNoShare, true, null);

                        database.CloseInput(true);

                        using (Transaction tr = database.TransactionManager.StartTransaction())
                        {
                            var bt = database.BlockTableId.GetObject(OpenMode.ForRead) as BlockTable;

                            //获取图形中的布局名称
                            var layouts = (DBDictionary)tr.GetObject(database.LayoutDictionaryId, OpenMode.ForRead);

                            //逐个布局进行处理
                            foreach (DBDictionaryEntry entry in layouts)
                            {
                                //获取某个布局
                                var layout = (Layout)tr.GetObject(entry.Value, OpenMode.ForRead);

                                //modelSpaceRB选中标识仅处理模型空间，如果循环项不是模型空间，那就跳过这个布局
                                if (modelSpaceRB.Checked && layout.BlockTableRecordId != bt[BlockTableRecord.ModelSpace])
                                {
                                    //MessageBox.Show(layout.LayoutName);
                                    continue;
                                }

                                //paperSpaceRB选中标识仅处理布局空间，如果循环项不是布局空间，那就跳过这个循环项
                                if (paperSpaceRB.Checked && layout.BlockTableRecordId != bt[BlockTableRecord.PaperSpace])
                                {
                                    //MessageBox.Show(layout.LayoutName);
                                    continue;
                                }
                                // layout 既可以 是模型空间也可以是布局空间，所以不用区分对待
                                var btr = (BlockTableRecord)tr.GetObject(layout.BlockTableRecordId, OpenMode.ForWrite);

                                foreach (ObjectId id in btr)
                                {
                                    //循环遍历Layout中的实体

                                    BlockReference block_Ref = tr.GetObject(id, OpenMode.ForRead) as BlockReference;

                                    if (block_Ref != null)
                                    {
                                        //思路是默认都处理，当指定了条件时，不满足条件的块就会被跳过

                                        string input = block_Ref.Name.Trim();
                                        //按理正图框块命名规则查找图框块，如果块名不能匹配，就跳过这个块
                                        if (radioButton3.Checked)
                                        {
                                            string pattern = @".*-A\d.*";

                                            if (Regex.IsMatch(input, pattern))
                                            {
                                            }
                                            else
                                            {
                                                continue;
                                            }
                                        }

                   
                                        
                                        if (radioButton7.Checked)
                                        {
                                            bool hasLZTKTag = false;

                                            // 获取块定义
                                            BlockTableRecord blockBtr = tr.GetObject(block_Ref.BlockTableRecord, OpenMode.ForRead) as BlockTableRecord;

                                            if (blockBtr == null)
                                            {
                                                continue;
                                            }

                                            // 遍历块定义中的所有实体
                                            List<string> entityList = new List<string>();

                                            foreach (ObjectId objIdInBlock in blockBtr)
                                            {

                                                Entity ent = tr.GetObject(objIdInBlock, OpenMode.ForRead) as Entity;

                                                if (ent != null && !ent.IsErased && ent is AttributeDefinition)
                                                {
                                                    AttributeDefinition attRef = (AttributeDefinition)ent;

                                                    if (attRef.Tag.Equals("LZFRAME", StringComparison.OrdinalIgnoreCase))
                                                    {
                                                        hasLZTKTag = true;
                                                        break;
                                                    }
                                                }
                                                
                                            }
                                            if (hasLZTKTag==false)
                                            {
                                                continue;
                                            }
                                            
                                        }
                                        
                                        if (block_Ref.AttributeCollection.Count > 0)
                                        {
                                            if (nms.Contains(block_Ref.Name) ==false)
                                            {
                                                nms.Add(block_Ref.Name);
                                            }
                                     
                                            //没有下面那行会导致对齐点有问题
                                            HostApplicationServices.WorkingDatabase = database;
                                            
                                            TkInfo tkInfo = new TkInfo();

                                            block_Ref.UpgradeOpen();

                                            ModifyTagString(database, tr, block_Ref, out tkInfo);
                                            

                                            if (tkInfo != null && tkInfo.HasInfo==true)
                                            {
                                         
                                                tkInfos_In_File.Add(tkInfo);
                                            }
                                        }
                                    }
                                }
                            }

                            //DO STUFF HERE
                            tr.Commit();
                        }

                        //database.SaveAs(drawingFilePath, true, DwgVersion.AC1021, null);

                        //有修改时才保存文件
                        if (checkBox1.Checked || checkBox2.Checked || checkBox3.Checked || checkBox4.Checked || checkBox5.Checked || checkBox6.Checked || checkBox7.Checked)
                        {
                            database.SaveAs(drawingFilePath, true, DwgVersion.Current, null);
                        }
                    }

                    //到这里就处理完了当前文件，记录下当前文件的一些信息
                    //将处理完的文件名，及其包含的图框名；
                    //fileNameAndTkNamesIn.Add(drawingFilePath, tkNames_In_File);

                    fileNameAndTkInfosIn.Add(drawingFilePath, tkInfos_In_File.OrderBy(x => x.TkNo).ThenBy(x => x.TkName).ThenBy(x => x.PageNo).ToList<TkInfo>());
                    
                }
                catch (Exception ee)
                {
                    fileNameAndTkNamesIn.Add(drawingFilePath, new List<string>() { "处理本文件时发生错误,跳过此文件", ee.ToString() });
                    //跳过当前文件
                    continue;
                }
            }

            string filePath = @"D:\批量修改图框信息记录文件.txt";

            // 使用StreamWriter写入文件
            using (StreamWriter writer = new StreamWriter(filePath))
            {
                //方案一 废止
                //foreach (var item in fileNameAndTkNamesIn)
                //{
                //    writer.WriteLine(item.Key);

                //    foreach (string tkName in item.Value)
                //    {
                //        // 写入每一项及两个空格

                //        writer.WriteLine(tkName);

                //    }
                //    writer.WriteLine();
                //}

                //方案二

                foreach (var item in fileNameAndTkInfosIn)
                {
                    writer.WriteLine(item.Key);

                    foreach (TkInfo tkInfo in item.Value)
                    {
                        // 写入每一项及两个空格

                        writer.WriteLine(tkInfo.ToString());
                    }
                    writer.WriteLine();
                }
            }

            using (StreamWriter writer = new StreamWriter(filePath, true))
            {
                writer.WriteLine("程序本运行处理的图框块有：");
                foreach (var item in nms)
                {
                    // 写入每一项及两个空格
                    writer.Write(item + " | ");
                }

                writer.WriteLine();
            }

            Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("everyThingIsOk");

            System.Diagnostics.Process.Start(filePath);

            this.Close();

            HostApplicationServices.WorkingDatabase = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument.Database;
        }

        private void ModifyTagString(Transaction transaction, BlockReference block_Ref)
        {
            string picNoAndName = string.Empty;

            foreach (ObjectId att_id in block_Ref.AttributeCollection)
            {
                AttributeReference attRef = transaction.GetObject(att_id, OpenMode.ForWrite) as AttributeReference;
                //if (attRef.Tag.ToString().Contains("日期"))
                //{
                //    attRef.TextString = "20300.12";
                //}
                if (checkBox1.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("工程名称"))
                    {
                        attRef.TextString = textBox2.Text;
                    }
                }
                if (checkBox2.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("项目名称"))
                    {
                        attRef.TextString = textBox3.Text;
                    }
                }

                if (checkBox3.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("版本"))
                    {
                        attRef.TextString = textBox4.Text;
                    }
                }

                if (checkBox4.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("工号"))
                    {
                        attRef.TextString = textBox5.Text;
                    }
                }

                if (checkBox5.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("阶段"))
                    {
                        attRef.TextString = textBox6.Text;
                    }
                }

                if (checkBox6.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("专业"))
                    {
                        attRef.TextString = textBox7.Text;
                    }
                }
                if (checkBox7.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("日期"))
                    {
                        attRef.TextString = textBox8.Text;
                    }
                }

                if (attRef.Tag.ToString().Contains("图号"))
                {
                    if (attRef.TextString != null)
                    {
                        picNoAndName = attRef.TextString;
                    }
                }

                if (attRef.Tag.ToString().Contains("图名"))
                {
                    if (attRef.TextString != null)
                    {
                        picNoAndName = picNoAndName + "-" + attRef.TextString;
                    }
                }
            }
        }

        private void ModifyTagString(Database database, Transaction transaction, BlockReference block_Ref, out string picNoAndName)
        {
            picNoAndName = string.Empty;

            string bianHao = string.Empty;

            string tuMIng = string.Empty;

            string pageNo = string.Empty;

            string pageSum = string.Empty;

            foreach (ObjectId att_id in block_Ref.AttributeCollection)
            {
                AttributeReference attRef = transaction.GetObject(att_id, OpenMode.ForWrite) as AttributeReference;

                if (checkBox1.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("工程名称"))
                    {
                        attRef.TextString = textBox2.Text;
                    }

                    attRef.Justify = AttachmentPoint.MiddleCenter;

                    attRef.AdjustAlignment(database);
                }
                if (checkBox2.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("项目名称"))
                    {
                        attRef.TextString = textBox3.Text;
                    }

                    attRef.Justify = AttachmentPoint.MiddleCenter;

                    attRef.AdjustAlignment(database);
                }

                if (checkBox3.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("版本"))
                    {
                        attRef.TextString = textBox4.Text;
                    }

                    attRef.Justify = AttachmentPoint.MiddleCenter;

                    attRef.AdjustAlignment(database);
                }

                if (checkBox4.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("工号"))
                    {
                        attRef.TextString = textBox5.Text;
                    }

                    attRef.Justify = AttachmentPoint.MiddleCenter;

                    attRef.AdjustAlignment(database);
                }

                if (checkBox5.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("阶段"))
                    {
                        attRef.TextString = textBox6.Text;
                    }

                    attRef.Justify = AttachmentPoint.MiddleCenter;

                    attRef.AdjustAlignment(database);
                }

                if (checkBox6.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("专业"))
                    {
                        attRef.TextString = textBox7.Text;
                    }

                    attRef.Justify = AttachmentPoint.MiddleCenter;

                    attRef.AdjustAlignment(database);
                }
                if (checkBox7.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("日期"))
                    {
                        attRef.TextString = textBox8.Text;
                    }

                    attRef.Justify = AttachmentPoint.MiddleCenter;

                    attRef.AdjustAlignment(database);
                }

                if (attRef.Tag.ToString().Contains("图纸编号"))
                {
                    if (attRef.TextString != null)
                    {
                        bianHao = attRef.TextString.Trim();
                    }
                }

                if (attRef.Tag.ToString().Contains("图纸名称") && !attRef.Tag.ToString().Contains("图纸名称1"))
                {
                    if (attRef.TextString != null)
                    {
                        tuMIng = attRef.TextString.Trim();
                    }
                }

                if (attRef.Tag.ToString().Contains("第页"))
                {
                    if (attRef.TextString != null)
                    {
                        pageNo = attRef.TextString.Trim();
                    }
                }
                if (attRef.Tag.ToString().Contains("总页"))
                {
                    if (attRef.TextString != null)
                    {
                        pageSum = attRef.TextString.Trim();
                    }
                }
            }

            picNoAndName = "第 " + pageNo + " 页" + " 共 " + pageSum + " 页 " + " 图纸编号: " + bianHao + " 图纸名称: " + tuMIng;
        }

        private void ModifyTagString(Database database, Transaction transaction, BlockReference block_Ref, out TkInfo tkInfo)
        {
            tkInfo = new TkInfo();

            //bool has_LZFRAME = false;

            //foreach (ObjectId att_id in block_Ref.AttributeCollection)
            //{
            //    AttributeReference attRef = transaction.GetObject(att_id, OpenMode.ForWrite) as AttributeReference;

            //    if (attRef.Tag.ToString().Contains("理正图框标识")|| attRef.Tag.ToString().Contains("LZFRAME"))
            //    {
            //        has_LZFRAME = true;

            //        break;
            //    }
            //}

            //block_Ref.UpgradeOpen();

            foreach (ObjectId att_id in block_Ref.AttributeCollection)
            {
                AttributeReference attRef = transaction.GetObject(att_id, OpenMode.ForWrite) as AttributeReference;

                if (attRef.Tag.ToString().Contains("LZFRAME"))
                {
                    Autodesk.AutoCAD.ApplicationServices.Application.ShowAlertDialog("找到图框");
                }

                if (checkBox1.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("工程名称"))
                    {
                        attRef.TextString = textBox2.Text;

                        attRef.Justify = AttachmentPoint.MiddleCenter;

                        attRef.AdjustAlignment(database);
                    }
                }
                if (checkBox2.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("项目名称"))
                    {
                        attRef.TextString = textBox3.Text;

                        attRef.AdjustAlignment(database);

                        attRef.Justify = AttachmentPoint.MiddleCenter;
                    }
                }

                if (checkBox3.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("版本"))
                    {
                        attRef.TextString = textBox4.Text;

                        attRef.Justify = AttachmentPoint.MiddleCenter;

                        attRef.AdjustAlignment(database);
                    }
                }

                if (checkBox4.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("工号"))
                    {
                        attRef.TextString = textBox5.Text;

                        attRef.Justify = AttachmentPoint.MiddleCenter;

                        attRef.AdjustAlignment(database);
                    }
                }

                if (checkBox5.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("阶段"))
                    {
                        attRef.TextString = textBox6.Text;

                        attRef.Justify = AttachmentPoint.MiddleCenter;

                        attRef.AdjustAlignment(database);
                    }
                }

                if (checkBox6.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("专业"))
                    {
                        attRef.TextString = textBox7.Text;

                        attRef.Justify = AttachmentPoint.MiddleCenter;

                        attRef.AdjustAlignment(database);
                    }
                }
                if (checkBox7.Checked == true)
                {
                    if (attRef.Tag.ToString().Contains("日期"))
                    {
                        attRef.TextString = textBox8.Text;

                        attRef.Justify = AttachmentPoint.MiddleCenter;

                        attRef.AdjustAlignment(database);
                    }
                }

                //下面内容用于在文件中输出图框的个性信息，需要考虑什么时候才需要写入

                //用于判断是否是理正图框，从而忽略一些不是图框块的信息记录
                
                if (attRef.Tag.ToString().Contains("图纸编号"))
                {
                    if (attRef.TextString != null)
                    {
                        tkInfo.TkNo = attRef.TextString.Trim();
                    }
                }

                if (attRef.Tag.ToString().Contains("图纸名称") && !attRef.Tag.ToString().Contains("图纸名称1"))
                {
                    if (attRef.TextString != null)
                    {
                        tkInfo.TkName = attRef.TextString.Trim();
                    }
                }

                if (attRef.Tag.ToString().Contains("第页"))
                {
                    int tmpInt = 0;
                    if (attRef.TextString != null)
                    {
                        if (int.TryParse(attRef.TextString, out tmpInt))
                        {
                            tkInfo.PageNo = tmpInt;
                        }
                    }
                }

                if (attRef.Tag.ToString().Contains("总页"))
                {
                    int tmpInt = 0;

                    if (attRef.TextString != null)
                    {
                        if (int.TryParse(attRef.TextString, out tmpInt))
                        {
                            tkInfo.PageTotal = tmpInt;
                        }
                    }
                }

                tkInfo.HasInfo = false;

                if (tkInfo.TkName!=null||tkInfo.TkNo!=null||tkInfo.PageNo>0||tkInfo.PageTotal>0)
                {
                    tkInfo.HasInfo = true;
                }
              
            }
        }

        private void ModifyTkInfoForm_Load(object sender, EventArgs e)
        {
            checkBox1.Checked = false;
            checkBox2.Checked = false;
            checkBox3.Checked = false;
            checkBox4.Checked = false;
            checkBox5.Checked = false;
            checkBox6.Checked = false;
            checkBox7.Checked = false;

            checkBox8.Checked = true;

      

            textBox2.Enabled = false;
            textBox3.Enabled = false;
            textBox4.Enabled = false;
            textBox5.Enabled = false;
            textBox6.Enabled = false;
            textBox7.Enabled = false;
            textBox8.Enabled = false;

            radioButton7.Checked = true;

      
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked == true)
            {
                textBox2.Enabled = true;
            }
            else
            {
                textBox2.Enabled = false;
            }
        }

        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked == true)
            {
                textBox3.Enabled = true;
            }
            else
            {
                textBox3.Enabled = false;
            }
        }

        private void checkBox3_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox3.Checked == true)
            {
                textBox4.Enabled = true;
            }
            else
            {
                textBox4.Enabled = false;
            }
        }

        private void checkBox4_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox4.Checked == true)
            {
                textBox5.Enabled = true;
            }
            else
            {
                textBox5.Enabled = false;
            }
        }

        private void checkBox5_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox5.Checked == true)
            {
                textBox6.Enabled = true;
            }
            else
            {
                textBox6.Enabled = false;
            }
        }

        private void checkBox6_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox6.Checked == true)
            {
                textBox7.Enabled = true;
            }
            else
            {
                textBox7.Enabled = false;
            }
        }

        private void checkBox7_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox7.Checked == true)
            {
                textBox8.Enabled = true;
            }
            else
            {
                textBox8.Enabled = false;
            }
        }

 



        private void button4_Click(object sender, EventArgs e)
        {
            int index = listBox1.SelectedIndex;

            string item = listBox1.SelectedItem as string;

            if (item!=null && dwgFiles.Contains(item))
            {
                dwgFiles.Remove(item);
            }
            else
            {
                return;
            }

            listBox1.Items.RemoveAt(listBox1.SelectedIndex);

            if (index > 0)
            {
                listBox1.SelectedIndex = index - 1;

            }
            else
            {
                if (listBox1.Items.Count > 0)
                {
                    listBox1.SelectedIndex = 0;
                }

            }

        }

        private void button5_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();

            dwgFiles.Clear();


        }

        private void listBox1_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                if (!e.Data.GetDataPresent(DataFormats.FileDrop))
                    return;

                Array paths = (Array)e.Data.GetData(DataFormats.FileDrop);

                foreach (string item in paths)
                {
                    if (Directory.Exists(item))
                    {
                        // 处理文件夹：直接搜索所有DWG文件
                        DirectoryInfo root = new DirectoryInfo(item);
                        FileInfo[] dwgFiles = root.GetFiles("*.dwg", SearchOption.AllDirectories);

                        foreach (var fileInfo in dwgFiles)
                        {
                            AddUniqueItem(listBox1, fileInfo.FullName);
                        }
                    }
                    else if (File.Exists(item) && IsDwgFile(item))
                    {
                        AddUniqueItem(listBox1, item);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"处理文件时出错: {ex.Message}", "错误",
                    MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private bool IsDwgFile(string filePath)
        {
            return Path.GetExtension(filePath)?.Equals(".dwg", StringComparison.OrdinalIgnoreCase) == true;
        }

        private void AddUniqueItem(ListBox listBox, string value)
        {
            if (!listBox.Items.Cast<string>().Any(x => x.Equals(value, StringComparison.OrdinalIgnoreCase)))
            {
                listBox.Items.Add(value);
            }
        }





   

        private void listBox1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.FileDrop))
                //e.Effect = DragDropEffects.All;    //重要代码：表明是所有类型的数据，比如文件路径

                e.Effect = DragDropEffects.Link;

            else
                e.Effect = DragDropEffects.None;
        }
    }
}